package sz.szsmk.citizencard.ui.dzsmkfragment;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.bumptech.glide.Glide;
import com.chenenyu.router.annotation.Route;

import javax.inject.Inject;

import sz.szsmk.citizencard.R;
import sz.szsmk.citizencard.log.L;
import sz.szsmk.citizencard.model.network.bean.response.AdvertisementsRes;
import sz.szsmk.citizencard.model.network.bean.response.BaseBean;
import sz.szsmk.citizencard.model.network.dzbean.res.MessageEvent;
import sz.szsmk.citizencard.model.network.dzbean.res.PreAuthResult;
import sz.szsmk.citizencard.model.network.dzbean.res.QrCodeNumberResult;
import sz.szsmk.citizencard.mvp.BasePresenter;
import sz.szsmk.citizencard.mvp.MainFragmentMvpView;
import sz.szsmk.citizencard.mvp.dzsmkpresenter.MainFragmentPresenter;
import sz.szsmk.citizencard.ui.dialogs.dzsmk.GreenTravelDialog;
import sz.szsmk.citizencard.ui.dzsmkavtivity.MainActivity;
import sz.szsmk.citizencard.ui.dzsmkavtivity.PayPwdSetActivity;
import sz.szsmk.citizencard.ui.dzsmkavtivity.RealNameAuthenticationActivity;
import sz.szsmk.citizencard.ui.dzsmkavtivity.RechargeActivity;
import sz.szsmk.citizencard.util.CommonUtils;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.JumpUtils;
import sz.szsmk.citizencard.util.PermissionUtil;
import sz.szsmk.citizencard.util.QrCodeUtils;
import sz.szsmk.citizencard.util.SecureSharedPreferences;
import sz.szsmk.citizencard.util.SmkUtil;
import sz.szsmk.citizencard.widget.GlobalVariables;

/**
 * Created by chensf on 17/9/30.
 *
 * 电子市名卡  首页
 */
@Route("dzsmkmain")
public class MainFragment extends AppBaseFragment implements OnFragmentRefresh, MainFragmentMvpView, View.OnClickListener {


    ImageView iv_qr_code;

    RelativeLayout cl_qr_code;
    ConstraintLayout cl_qr_no_net;
    ConstraintLayout cl_qr_other;
    LinearLayout cl_qr_limit;

    TextView tv_qr_other_tip;
    ImageView iv_qr_other;
    Button btn_qr_other;

    TextView is_acard_tv;

    @Inject
    MainFragmentPresenter mMainFragmentPresenter;


    TextView dzsmkCcjl;


    TextView tv_showQRagain;

    private PreAuthResult preAuthResult = null;
    private boolean refresh = false;

    ImageView iv_discount;

    TextView tv_realtiem_bus;

    TextView tv_yuechaxun;

    @Override
    protected CharSequence getTopTitle() {
        return "";
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.qr_fragment_main, container, false);
        getComponent().inject(this);

        iv_qr_code = view.findViewById(R.id.iv_qr_code);

        iv_qr_code.setOnClickListener(this);

        cl_qr_code = view.findViewById(R.id.cl_qr_code);

        cl_qr_no_net = view.findViewById(R.id.cl_qr_no_net);

        cl_qr_other = view.findViewById(R.id.cl_qr_other);

        cl_qr_limit = view.findViewById(R.id.cl_qr_limit);

        tv_qr_other_tip = view.findViewById(R.id.tv_qr_other_tip);

        iv_qr_other = view.findViewById(R.id.iv_qr_other);

        btn_qr_other = view.findViewById(R.id.btn_qr_other);

        btn_qr_other.setOnClickListener(this);

        is_acard_tv = view.findViewById(R.id.is_acard_tv);

        dzsmkCcjl = view.findViewById(R.id.dzsmk_ccjl);
        dzsmkCcjl.setOnClickListener(this);
        tv_showQRagain = view.findViewById(R.id.tv_showQRagain);
        tv_showQRagain.setOnClickListener(this);
        iv_discount = view.findViewById(R.id.iv_discount);

        tv_realtiem_bus = view.findViewById(R.id.tv_realtiem_bus);
        tv_realtiem_bus.setOnClickListener(this);


        tv_yuechaxun = view.findViewById(R.id.tv_yuechaxun);
        tv_yuechaxun.setOnClickListener(this);

        return view;
    }

    GreenTravelDialog dialog;

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        MainActivity mainActivity = (MainActivity) getActivity();
        mainActivity.showQrNavMenu();
        dialog = new GreenTravelDialog(getContext());

    }

    public void startGdLocation() {
        changeBrightness();
        SecureSharedPreferences.putString(Constant.LONGITUDE, "120.610960");
        SecureSharedPreferences.putString(Constant.LATITUDE, "31.328800");
        mMainFragmentPresenter.getQrNumber();
    }

    @Override
    public void onResume() {
        super.onResume();
        mMainFragmentPresenter.getPersonInfo();
        mMainFragmentPresenter.getAdvertisements();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if(dialog.isShowing()){
            dialog.dismiss();
        }
    }

    @Override
    protected BasePresenter[] initPresenters() {
        return new BasePresenter[]{mMainFragmentPresenter};
    }

    @Override
    public void onRefresh() {
        changeBrightness();
        preAuthResult = GlobalVariables.getInstance(getContext()).getPreAuthResult();
        if (refresh) {
            refresh = false;
            preAuthSuccess();
        }
    }

    @Override
    public void onEvent(MessageEvent event) {
        if (MessageEvent.CODE_REFRESH == event.getCode()) {
            refresh = true;
            onRefresh();
        } else if (MessageEvent.CODE_UPDATE_USERINFO_SUCCESS == event.getCode() ||
                MessageEvent.CODE_UPDATE_BALANCE_SUCCESS == event.getCode() || MessageEvent.CODE_REFRESH_CODE == event.getCode()) {
            refresh = true;
        }
    }

    private void changeBrightness() {
        int systemBrightness = SmkUtil.getSystemBrightness(getActivity());
        if (systemBrightness < 255) {
            SmkUtil.changeSystemBrightness(getActivity().getWindow(), 255);
        }
    }

    public void setMainFragmentVisible(boolean visible) {
        //若是显示时，则暂停刷新肯定要false了
        if (null != mMainFragmentPresenter) {
            mMainFragmentPresenter.setPauseRefresh(!visible);
        }
    }

    public boolean isShowingRefreshQrCode() {
        if (null != mMainFragmentPresenter) {
            return mMainFragmentPresenter.isShowingCode();
        } else {
            return false;
        }
    }

    public void refreshQrCode() {
        mMainFragmentPresenter.forceRefresh();
    }

    public void onClickView(View v) {
        if (R.id.iv_qr_code == v.getId()) {
            PreAuthResult preAuthResult = GlobalVariables.getInstance(getContext()).getPreAuthResult();
            if (preAuthResult == null) {
                return;
            }
            mMainFragmentPresenter.forceRefresh();
        } else if (R.id.btn_qr_other == v.getId()) {
            String mType = preAuthResult.getUserStatus();
            if (Constant.QUERY_QR_RESULT_NO_AUTH.equals(mType)) { //实名认证
                Intent intent = new Intent(getActivity(), RealNameAuthenticationActivity.class);
                intent.putExtra("isRealName", "0");
                intent.putExtra("MainFragment", true);
                startActivity(intent);
            } else if (Constant.QUERY_QR_RESULT_NO_ENOUGH_BALANCE.equals(mType)) { //余额不足
                Intent intent = new Intent(getActivity(), RechargeActivity.class);
                intent.putExtra("MainFragment", true);
                startActivity(intent);
            } else if (Constant.QUERY_QR_RESULT_NO_PAY_PWD_SET.equals(mType)) { //设置密码
                Intent intent = new Intent(getActivity(), PayPwdSetActivity.class);
                intent.putExtra("MainFragment", true);
                intent.putExtra("type", true);
                startActivity(intent);
            }
        }
    }

    @Override
    public void onGainQrCodeNumber(QrCodeNumberResult qrCodeNumberResult) {
        showConstraintLayout(qrCodeNumberResult.getResultCode());

        if (Constant.QUERY_QR_RESULT_AUTHED.equals(qrCodeNumberResult.getResultCode())) {
            iv_qr_code.setEnabled(true);
            String qrCode = qrCodeNumberResult.getQrCode();
            L.e(System.currentTimeMillis() + "========>qrCode:" + qrCode);
            int width = iv_qr_code.getWidth();
            try {
                Bitmap logo = BitmapFactory.decodeResource(getResources(), R.drawable.logo);
                Bitmap bitmap = QrCodeUtils.createQRCode(logo, qrCode, width, width / 5);
                iv_qr_code.setImageBitmap(bitmap);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            handlerOtherStatus(qrCodeNumberResult.getResultCode());
        }

    }

    @Override
    public void onGainQrCodeException() {
        cl_qr_code.setVisibility(View.VISIBLE);
        cl_qr_no_net.setVisibility(View.GONE);
        cl_qr_other.setVisibility(View.GONE);
        cl_qr_limit.setVisibility(View.GONE);
        iv_qr_code.setEnabled(false);
    }

    @Override
    public void getAcardSucc(BaseBean response) {
        if (response != null) {
            String state = response.getState();
            if (state != null) {
                if (state.equals("0")) {
                    //无A卡
                    is_acard_tv.setVisibility(View.GONE);
                } else {
                    is_acard_tv.setVisibility(View.VISIBLE);
                }
            }
        }
    }

    private void handlerOtherStatus(String resultCode) {
        if (Constant.QUERY_QR_RESULT_NO_AUTH.equals(resultCode)) { //需要实名认证
            btn_qr_other.setText(R.string.qr_realname_auth);
            iv_qr_other.setImageResource(R.drawable.qr_code_go_auth);
            tv_qr_other_tip.setText(R.string.qr_please_auth);
        } else if (Constant.QUERY_QR_RESULT_NO_ENOUGH_BALANCE.equals(resultCode)) { //余额不足
            btn_qr_other.setText(R.string.qr_no_enough_balance);
            iv_qr_other.setImageResource(R.drawable.qr_code_no_enough_balance);
            tv_qr_other_tip.setText(R.string.qr_recharge);
            preAuthResult.setUserStatus(Constant.QUERY_QR_RESULT_NO_ENOUGH_BALANCE);
            GlobalVariables.getInstance(getContext()).setPreAuthResult(getContext(), preAuthResult);
        } else if (Constant.QUERY_QR_RESULT_NO_PAY_PWD_SET.equals(resultCode)) { //设置密码
            btn_qr_other.setText(R.string.qr_please_set_paypwd);
            iv_qr_other.setImageResource(R.drawable.qr_code_set_pay_pwd);
            tv_qr_other_tip.setText(R.string.qr_set_paypwd);
        } else if (Constant.QUERY_QR_RESULT_OTHER.equals(resultCode)) {

        }
    }

    private void showConstraintLayout(String type) {
        cl_qr_code.setVisibility(View.GONE);
        cl_qr_no_net.setVisibility(View.GONE);
        cl_qr_other.setVisibility(View.GONE);
        cl_qr_limit.setVisibility(View.GONE);
        if (Constant.QUERY_QR_RESULT_AUTHED.equals(type)) {
            cl_qr_code.setVisibility(View.VISIBLE);
        } else if (Constant.QUERY_QR_RESULT_NO_NET.equals(type)) {
            cl_qr_no_net.setVisibility(View.VISIBLE);
        } else if (Constant.QUERY_QR_RESULT_OTHER.equals(type)) {
            cl_qr_limit.setVisibility(View.VISIBLE);
        } else {
            cl_qr_other.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onNoQrCodeUsed() {
        //没有联网，请联网，查看是否实名，或生成的码全部过期需要全部生成
        showNoNetStatus();
    }

    public void preAuthSuccess() {
        preAuthResult = GlobalVariables.getInstance(getContext()).getPreAuthResult();
        if (preAuthResult == null) {
            return;
        }
        showConstraintLayout(preAuthResult.getUserStatus());
        handlerOtherStatus(preAuthResult.getUserStatus());

        if (preAuthResult.getUserStatus().equals(Constant.QUERY_QR_RESULT_AUTHED)) {
            startGdLocation();

        }
    }

    private void showNoNetStatus() {
        if (!CommonUtils.hasNetwork(getActivity())) {
            showConstraintLayout(Constant.QUERY_QR_RESULT_NO_NET);
        }
    }


    @Override
    public void onPause() {
        super.onPause();
    }



    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.dzsmk_ccjl) {
            Bundle bundle = new Bundle();
            bundle.putString("type", "0");
            JumpUtils.jumptoNatvie(getActivity(), "dzsmkuser", 0, bundle);
        } else if (id == R.id.tv_showQRagain) {//刷新二维码
            mMainFragmentPresenter.forceRefresh();
        } else if (id == R.id.tv_yuechaxun) {
            Bundle bundle1 = new Bundle();
            bundle1.putString("type", "1");
            JumpUtils.jumptoNatvie(getActivity(), "dzsmkuser", 0, bundle1);
        } else if (id == R.id.tv_realtiem_bus) {
            JumpUtils.jump(getActivity(), "BusHomeActivity", 0);
        }
    }

    @Override
    public void getAdvertisementsResult(AdvertisementsRes advertisementsRes) {

        Glide.with(getContext()).load(advertisementsRes.getData().getImgUrl()).into(iv_discount);
        iv_discount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.show();
                dialog.setData(advertisementsRes);
            }
        });

    }


    @Override
    public void onClick(View v) {
        onClickView(v);
        onViewClicked(v);
    }
}
